package ws

import (
	"context"
	"net"

	"golang.org/x/net/websocket"

	"gitee.com/hasika/common-server/conn/impl_base"
	"gitee.com/hasika/common-server/conn/inet"
)

func init() {
}

type Connection struct {
	*websocket.Conn
	*impl_base.Connection
	cancel context.CancelFunc
	ctx    context.Context
}

func (t *Connection) GetRemote() net.Addr {
	return t.Conn.RemoteAddr()
}

func (t *Connection) InitFd() {
	//tcpConn := reflect.Indirect(reflect.ValueOf(t.Conn)).FieldByName("rwc").Interface().(*conn.TCPConn)
	//t.SetFd(fd.SocketFD(tcpConn))
}

func NewWebsocketConnection(WebsocketConn *websocket.Conn, parent context.Context) *Connection {
	ctx, cancel := context.WithCancel(parent)
	wc := &Connection{Conn: WebsocketConn, Connection: impl_base.NewBaseConnection(), cancel: cancel, ctx: ctx}
	return wc
}

func (t *Connection) GetConnectionType() inet.ConnectionType {
	return inet.Websocket
}

func (t *Connection) CloseConn() error {
	return t.Conn.Close()
}

func (t *Connection) LowerWrite(data []byte) error {
	return websocket.Message.Send(t.Conn, data)
}
func (t *Connection) Close() error {
	t.cancel()
	return t.Conn.Close()
}
